<template>
  <div class="flowStatisticsPage h100">

    <!-- 月度流量统计 -->
    <h2 class="title18 mb8">{{ $t('ydlltj') }}</h2>
    <a-row :gutter="[16,16]">
      <!-- 选择车型 -->
      <a-col
        :xs="24"
        :sm="12"
        :md="12"
        :lg="8"
        :xl="8"
        :xxl="6"
      >
        <car-model-select
          ref="selectModel"
          :defaultValue="queryParams.modelId"
          @changeoption="selectCarModel"
          @transSelecetdModelObj="recordModelNameMonth"
          @selectFirstTimeDone="handleMonthModelSelectFirst"
          :hasAll="false"
          :clear="false"
          mode="default"
          style="width: 100%;"
          :selectFirstOption="true"
        />
      </a-col>
      <!-- 选择任务 -->
      <a-col
        :xs="24"
        :sm="12"
        :md="8"
        :lg="6"
        :xl="6"
        :xxl="6"
      >
        <a-select
          show-search
          option-filter-prop="children"
          :filterOption="$commonFun.filterOption"
          :getPopupContainer="$commonFun.getPopupContainer"
          :placeholder="$t(taskPlaceholder)"
          :allowClear="true"
          mode="default"
          style="width: 100%;"
          v-model="queryParams.taskId"
        >
          <a-select-option v-for="item in taskOptions" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
        </a-select>
      </a-col>
      <!-- 选择月份 -->
      <a-col
        :xs="24"
        :sm="12"
        :md="12"
        :lg="8"
        :xl="8"
        :xxl="6"
      >
        <a-range-picker
          @panelChange="handlePanelChange"
          :value="defaultMonthRange"
          :allow-clear="false"
          :mode="rangePickerMode"
          format="YYYY-MM"
        />
      </a-col>
      <!-- 操作框,查询/重置/导出 -->
      <a-col
        :xs="24"
        :sm="12"
        :md="12"
        :lg="8"
        :xl="8"
        :xxl="6"
      >
        <auth-button type="info" style="margin: 0 10px" :auth="statisticsPerms.flow.view" @click="searchMonthData">
          <i class="iconfont icon-chazhao"></i>
          {{ $t('inquiry') }}
        </auth-button>
        <a-button @click="clearCondition" style="margin-right: 10px">
          <i class="iconfont icon-qingkong"></i>
          {{ $t('clear') }}
        </a-button>
        <auth-button
          type="primary"
          :loading="exportingMonth"
          :auth="statisticsPerms.flow.export"
          @click="exportStatisticsMonth"
        >
          <i class="iconfont icon-xiazai"></i>
          {{ $t('export') }}
        </auth-button>
      </a-col>
    </a-row>
    <div style="height:500px">
      <LineAndBarEchart :chartOption="chartOption" :loading="requesting"/>
    </div>

    <!-- 流量时段统计 -->
    <h2 class="title18 mb8">{{ $t('llsdtj') }}</h2>
    <a-row :gutter="[16,24]">
      <a-col :lg="6" :sm="12">
        <car-model-select
          ref="selectModelDate"
          :defaultValue="queryParamsDate.modelId"
          @changeoption="selectCarModelByHour"
          @transSelecetdModelObj="recordModelNameDate"
          @selectFirstTimeDone="handleDateModelSelectFirst"
          :hasAll="false"
          :clear="false"
          mode="default"
          style="width: 100%;"
          :selectFirstOption="true"
        />
      </a-col>
      <a-col :lg="6" :sm="12">
        <a-range-picker
          @change="onDayRangeChange"
          :value="defaultDateRange"
          :allow-clear="false"
          format="YYYY-MM-DD"
        />
      </a-col>
      <a-col
        :xs="24"
        :sm="12"
        :md="12"
        :lg="8"
        :xl="8"
        :xxl="6"
      >
        <auth-button type="info" style="margin: 0 10px" :auth="statisticsPerms.flow.view" @click="searchDateData">
          <i class="iconfont icon-chazhao"></i>
          {{ $t('inquiry') }}
        </auth-button>
        <a-button @click="clearDateCondition" style="margin-right: 10px">
          <i class="iconfont icon-qingkong"></i>
          {{ $t('clear') }}
        </a-button>
        <auth-button
          type="primary"
          :loading="exportingDate"
          :auth="statisticsPerms.flow.export"
          @click="exportStatisticsDate"
        >
          <i class="iconfont icon-xiazai"></i>
          {{ $t('export') }}
        </auth-button>
      </a-col>
    </a-row>
    <div style="height:500px">
      <LineAndBarEchart :chartOption="dateChartOption" :loading="requestingDate"/>
    </div>

  </div>
</template>
<script>
import moment from 'moment'
// 引入任务模块接口
import taskApi from '@/api/modules/task'
// 引入自定义的折线图和柱状图混合的echarts组件
import LineAndBarEchart from './components/LineAndBarEchart.vue'
// 引入车型选择器
import CarModelSelect from '@/views/components/CarModelSelect'
// 引入统计权限
import { statisticsPerms } from '@/config/permission/index'
// 引入权限按钮
import AuthButton from '@/components/AuthButton'
// 引入统计模块接口
import statisticsApi from '@/api/modules/statistics'
// 引入下载工具
import { downloadBlobFile } from '@/utils/functions'
export default {
  components: {
    LineAndBarEchart,
    CarModelSelect,
    AuthButton
  },
  data () {
    return {
      queryParams: {
        taskId: undefined,
        modelId: undefined,
        startTime: moment().subtract(11, 'month').format('YYYY-MM'),
        endTime: moment().format('YYYY-MM')
      },
      queryParamsDate: {
        modelId: undefined,
        startTime: moment().subtract(30, 'days').format('YYYY-MM-DD'),
        endTime: moment().format('YYYY-MM-DD')
      },
      statisticsPerms,
      rangePickerMode: ['month', 'month'],
      exportingMonth: false,
      exportingDate: false,
      defaultDateRange: [moment().subtract(29, 'days').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')],
      defaultMonthRange: [moment().subtract(11, 'month').format('YYYY-MM'), moment().format('YYYY-MM')],
      taskOptions: [],
      chartOption: {},
      requesting: false,
      requestingDate: false,
      dateChartOption: {},
      exportMonthQuery: {},
      exportDateQuery: {},
      exportMonthModelObj: {},
      exportDateModelObj: {},
      taskPlaceholder: 'noData'
    }
  },
  methods: {
    // 月度统计-默认选中车型完成
    handleMonthModelSelectFirst () {
      this.searchMonthData()
    },
    // 时段统计-默认选中车型完成
    handleDateModelSelectFirst () {
      this.searchDateData()
    },
    // 保存月度统计组件传递上来的选中的车型选项，其中包含导出表格时需要的车型名称等
    recordModelNameMonth (val) {
      this.exportMonthModelObj = val
    },
    // 保存时段统计组件传递上来的选中的车型选项，其中包含导出表格时需要的车型名称等
    recordModelNameDate (val) {
      this.exportDateModelObj = val
    },
    // 点击查询时段统计
    searchDateData () {
      this.requestingDate = true
      // eslint-disable-next-line prefer-destructuring
      this.queryParamsDate.startTime = this.defaultDateRange[0]
      // eslint-disable-next-line prefer-destructuring
      this.queryParamsDate.endTime = this.defaultDateRange[1]
      this.exportDateQuery = this.queryParamsDate
      statisticsApi.getFlowChartByHour(this.queryParamsDate).then((res) => {
        if (res.data) {
          this.dateChartOption = res.data
        } else {
          this.dateChartOption = {}
        }
      }).finally(() => {
        this.requestingDate = false
      })
    },
    // 点击查询月度统计
    searchMonthData () {
      this.requesting = true
      // eslint-disable-next-line prefer-destructuring
      this.queryParams.startTime = this.defaultMonthRange[0]
      // eslint-disable-next-line prefer-destructuring
      this.queryParams.endTime = this.defaultMonthRange[1]
      this.exportMonthQuery = this.queryParams
      statisticsApi.getMonthlyFlowChart(this.queryParams).then((res) => {
        if (res.data) {
          this.chartOption = res.data
        } else {
          this.chartOption = {}
        }
      }).finally(() => {
        this.requesting = false
      })
    },
    // 清空流量月份统计的搜索条件
    clearCondition () {
      this.queryParams.startTime = moment().subtract(30, 'days').format('YYYY-MM')
      this.queryParams.endTime = moment().format('YYYY-MM')
      this.queryParams.taskId = undefined
      this.$refs.selectModel.recoverToFirstOption()
      this.defaultMonthRange = [moment().subtract(11, 'month').format('YYYY-MM'), moment().format('YYYY-MM')]
      // this.searchMonthData()
    },
    // 清空时段统计的搜索条件
    clearDateCondition () {
      this.queryParamsDate.startTime = moment().subtract(30, 'days').format('YYYY-MM-DD')
      this.queryParamsDate.endTime = moment().format('YYYY-MM-DD')
      this.$refs.selectModelDate.recoverToFirstOption()
      this.defaultDateRange = [moment().subtract(30, 'days').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
      // this.searchDateData()
    },
    // 导出月份统计表格
    exportStatisticsMonth () {
      this.exportingMonth = true
      this.$api.exportFlowStasticsReport(this.exportMonthQuery).then((res) => {
        // eslint-disable-next-line max-len
        downloadBlobFile(res, this.$t('ydlltj') + '[' + this.exportMonthModelObj.title + '][' + this.exportMonthModelObj.trimLevel + ']' + '.xlsx')
      }).finally(() => {
        this.exportingMonth = false
      })
    },
    // 导出时段统计表格
    exportStatisticsDate () {
      this.exportingDate = true
      this.$api.exportFlowDetailReport(this.exportDateQuery).then((res) => {
        // eslint-disable-next-line max-len
        downloadBlobFile(res, this.$t('llsdtj') + '[' + this.exportMonthModelObj.title + '][' + this.exportMonthModelObj.trimLevel + ']' + '.xlsx')
      }).finally(() => {
        this.exportingDate = false
      })
    },
    // 选择车型
    selectCarModel (val, val2) {
      this.queryParams.taskId = undefined
      this.queryParams.modelId = val
      // 车型被手动恢复到第一条之后，手动去请求数据
      if (val2) {
        this.searchMonthData()
      }
      // 请求任务下拉
      taskApi.getTaskSelect({ modelId: val, type: [1, 2] }).then((res) => {
        this.taskOptions = []
        if (Array.isArray(res.data) && res.data.length > 0) {
          this.taskOptions = res.data.map(item => {
            return {
              id: item.id,
              name: item.name
            }
          })
          this.taskPlaceholder = 'pleaseSelect'
        } else {
          this.taskPlaceholder = 'noData'
        }
      }).catch(() => {
        this.taskPlaceholder = 'noData'
      })
    },
    // 选择车型-流量时段
    selectCarModelByHour (val, val2) {
      this.queryParamsDate.modelId = val
      // 车型被手动恢复到第一条之后，手动去请求数据
      if (val2) {
        this.searchDateData()
      }
    },
    // 选择切换任务
    changeTask (val) {
      this.queryParams.taskId = val
    },
    // 月份范围选择器不能触发onchange事件,需要根据panelChange事件自己写逻辑
    handlePanelChange (value, mode) {
      const maxMonths = 12
      if (value[1].diff(value[0], 'months') >= maxMonths) {
        this.$message.error(this.$t('monthRangeTip').replace('__MONTHS__', maxMonths))
        return
      }
      this.defaultMonthRange = [value[0].format('YYYY-MM'), value[1].format('YYYY-MM')]
      this.rangePickerMode = [mode[0] === 'date' ? 'month' : mode[0], mode[1] === 'date' ? 'month' : mode[1]]
    },
    // 选择切换日期范围
    onDayRangeChange (date, dateString) {
      if (date.length === 0) {
        this.queryParamsDate.startTime = moment().subtract(1, 'months').format('YYYY-MM-DD')
        this.queryParamsDate.endTime = moment().endOf('day').format('YYYY-MM-DD')
        return
      }
      const maxDays = 30
      if (date[1].diff(date[0], 'days') >= maxDays) {
        this.$message.error(this.$t('dateRangeTip').replace('__DAYS__', maxDays))
        // eslint-disable-next-line consistent-return
        return false
      }
      // eslint-disable-next-line prefer-destructuring
      this.queryParamsDate.startTime = dateString[0]
      // eslint-disable-next-line prefer-destructuring
      this.queryParamsDate.endTime = dateString[1]
      this.defaultDateRange = dateString
    }
  }

}
</script>
<style lang="less" scoped>
.flowStatisticsPage{
  padding: 16px 32px;
}
</style>
